package com.wuuxiang.polestar.core.zookeeper;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.wuuxiang.polestar.core.ConfigProfile;
import org.apache.curator.RetryPolicy;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.utils.ZKPaths;

/**********************************************************
 * 项目名称：polestar
 * 类描述：   
 * 创建人：夏鸿鹏 
 * 创建时间：2017-11-24 18:33   
 * 修改备注：   
 *
 **********************************************************/

public class ZookeeperConfigProfile extends ConfigProfile {

    // 重试策略
    private static final ExponentialBackoffRetry DEFAULT_RETRY_POLICY = new ExponentialBackoffRetry(
            1000, 3);

    /**
     * zookeeper地址
     */
    private final String connectStr;

    /**
     * 项目配置根目录
     */
    private final String rootNode;

    /**
     * 重试策略
     */
    private final RetryPolicy retryPolicy;

    /**
     * 是否开启本地缓存, 基础为当前用户目录下的.polestar
     */
    private final boolean openLocalCache;


    public ZookeeperConfigProfile(final String connectStr,
                                  final String rootNode, final String version) {
        this(connectStr, rootNode, version, false);
    }

    public ZookeeperConfigProfile(final String connectStr,
                                  final String rootNode, final String version,
                                  final boolean openLocalCache) {
        this(connectStr, rootNode, version, openLocalCache,
                DEFAULT_RETRY_POLICY);
    }

    public ZookeeperConfigProfile(final String connectStr,
                                  final String rootNode, final String version,
                                  final boolean openLocalCache, final RetryPolicy retryPolicy) {
        super(version);
        this.connectStr = Preconditions.checkNotNull(connectStr);
        this.rootNode = Preconditions.checkNotNull(rootNode);
        this.retryPolicy = Preconditions.checkNotNull(retryPolicy);
        this.openLocalCache = openLocalCache;
    }

    public String getConnectStr() {
        return connectStr;
    }

    public String getRootNode() {
        return rootNode;
    }

    public RetryPolicy getRetryPolicy() {
        return retryPolicy;
    }

    public String getVersionedRootNode() {
        if (Strings.isNullOrEmpty(version)) {
            return rootNode;
        }
        return ZKPaths.makePath(rootNode, version);
    }

    public boolean isOpenLocalCache() {
        return openLocalCache;
    }

    @Override
    public String toString() {
        return "ZookeeperConfigProfile{" + "connectStr='" + connectStr + '\''
                + ", rootNode='" + rootNode + '\'' + ", retryPolicy="
                + retryPolicy + ", openLocalCache=" + openLocalCache + '}';
    }

}
